import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../models/article.dart';
import '../services/api_service.dart';
import '../widgets/article_card.dart';
import '../config/app_theme.dart';
import '../config/app_config.dart';

/// 播放历史页面
class HistoryScreen extends StatefulWidget {
  const HistoryScreen({super.key});

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> {
  final ApiService _apiService = ApiService();
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  final List<Article> _historyList = [];
  int _pageNum = 1;
  int _total = 0;
  bool _loading = false;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData({bool refresh = false}) async {
    if (_loading) return;
    
    setState(() => _loading = true);
    
    if (refresh) {
      _pageNum = 1;
    }
    
    try {
      final response = await _apiService.getPlayHistory(
        pageNum: _pageNum,
        pageSize: AppConfig.pageSize,
      );
      
      final List<dynamic> rows = response.data['data']['rows'] ?? [];
      
      if (refresh) {
        _historyList.clear();
      }
      
      _historyList.addAll(rows.map((json) => Article.fromJson(json)).toList());
      _total = response.data['data']['total'] ?? 0;
      
      setState(() => _loading = false);
    } catch (e) {
      setState(() => _loading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: $e')),
        );
      }
    }
  }

  Future<void> _onRefresh() async {
    await _loadData(refresh: true);
    _refreshController.refreshCompleted();
  }

  Future<void> _onLoading() async {
    if (_historyList.length >= _total) {
      _refreshController.loadNoData();
      return;
    }
    
    _pageNum++;
    await _loadData();
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('播放历史'),
      ),
      body: _loading && _historyList.isEmpty
          ? const Center(child: CircularProgressIndicator())
          : _historyList.isEmpty
              ? const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.history, size: 64, color: AppTheme.textTertiary),
                      SizedBox(height: 16),
                      Text(
                        '暂无播放历史',
                        style: TextStyle(
                          color: AppTheme.textTertiary,
                          fontSize: 16,
                        ),
                      ),
                    ],
                  ),
                )
              : SmartRefresher(
                  controller: _refreshController,
                  enablePullDown: true,
                  enablePullUp: true,
                  onRefresh: _onRefresh,
                  onLoading: _onLoading,
                  child: ListView.builder(
                    padding: const EdgeInsets.all(16),
                    itemCount: _historyList.length,
                    itemBuilder: (context, index) {
                      return ArticleCard(article: _historyList[index]);
                    },
                  ),
                ),
    );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}

